package com.hand.demo.app.service.impl;

import com.hand.demo.domain.entity.GsjExample;
import com.hand.demo.domain.repository.GsjExampleRepository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.stream.Collectors;
import io.choerodon.mybatis.domain.AuditDomain;
import java.util.Map;

import org.springframework.stereotype.Service;
import com.hand.demo.app.service.GsjExampleService;
import java.util.List;

import org.hzero.mybatis.helper.UniqueHelper;

/**
 * 应用服务默认实现
 *
 * @author sijia.guo01@hand-china.com 2023-09-22 17:20:31
 */
@Service
public class GsjExampleServiceImpl implements GsjExampleService {
                                                
    @Autowired
    private GsjExampleRepository gsjExampleRepository;


    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<GsjExample> batchSave(List<GsjExample> gsjExampleList) {
        Map<AuditDomain.RecordStatus, List<GsjExample>> statusMap = gsjExampleList.stream().collect(Collectors.groupingBy(GsjExample::get_status));
        // 删除
        if (statusMap.containsKey(AuditDomain.RecordStatus.delete)) {
            List<GsjExample> deleteList = statusMap.get(AuditDomain.RecordStatus.delete);
            gsjExampleRepository.batchDeleteByPrimaryKey(deleteList);
        }
        // 更新
        if (statusMap.containsKey(AuditDomain.RecordStatus.update)) {
            List<GsjExample> updateList = statusMap.get(AuditDomain.RecordStatus.update);
            updateList.forEach(item -> {
                // TODO: 唯一性校验
                UniqueHelper.valid(item,GsjExample.GSJ_EXAMPLE_U1);
                gsjExampleRepository.updateByPrimaryKeySelective(item);
            });
        }
        // 新增
        if (statusMap.containsKey(AuditDomain.RecordStatus.create)) {
            List<GsjExample> createList = statusMap.get(AuditDomain.RecordStatus.create);
            createList.forEach(item -> {
                // TODO: 唯一性校验
                UniqueHelper.valid(item,GsjExample.GSJ_EXAMPLE_U1);
                gsjExampleRepository.insertSelective(item);
            });
        }
        return gsjExampleList;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public GsjExample save(GsjExample gsjExample) {
        //保存
        UniqueHelper.valid(gsjExample,GsjExample.GSJ_EXAMPLE_U1);
        if (gsjExample.getId() == null) {
            gsjExampleRepository.insertSelective(gsjExample);
        } else {
            gsjExampleRepository.updateOptional(gsjExample,
                    GsjExample.FIELD_CODE,
                    GsjExample.FIELD_NAME,
                    GsjExample.FIELD_TENANT_ID
            );
        }

        return gsjExample;
    }
}
